package com.example.service;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 巨型订单服务 - 包含所有订单相关业务逻辑的超大类
 * 这是一个违反单一职责原则的典型屎山代码
 */
@Service
public class MegaOrderService {
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired  
    private NotificationService notificationService;
    
    @Autowired
    private InventoryService inventoryService;
    
    @Autowired
    private ShippingService shippingService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private DiscountService discountService;
    
    @Autowired
    private LogService logService;
    
    // 大量魔法值
    public static final String ORDER_STATUS_PENDING = "PENDING";
    public static final String ORDER_STATUS_CONFIRMED = "CONFIRMED";
    public static final String ORDER_STATUS_SHIPPED = "SHIPPED";
    public static final String ORDER_STATUS_DELIVERED = "DELIVERED";
    public static final String ORDER_STATUS_CANCELLED = "CANCELLED";
    public static final String PAYMENT_METHOD_CREDIT_CARD = "CREDIT_CARD";
    public static final String PAYMENT_METHOD_PAYPAL = "PAYPAL";
    public static final String PAYMENT_METHOD_BANK_TRANSFER = "BANK_TRANSFER";
    
    // 应该封装的public字段
    public String systemName = "OrderManagementSystem";
    public String version = "1.0.0";
    public int maxOrderItems = 100;
    public double taxRate = 0.15;
    public boolean isPromotionActive = true;
    public long maxProcessingTime = 30000;
    
    /**
     * 创建订单 - 超长方法包含所有业务逻辑 (预计超过80行)
     */
    public OrderResult createOrder(String userId, String productId, int quantity, String paymentMethod, 
                                 String shippingAddress, String discountCode, boolean isGiftWrap, 
                                 String giftMessage, String preferredDeliveryTime, boolean isUrgent) {
        
        System.out.println("开始创建订单...");
        
        User user;
        user = createOrderPart1();
        
        if (!user.isActive()) {
            throw new RuntimeException("用户账户已被禁用");
        }
        createOrderPart2(user);
        }
        
        // 产品验证
        createOrderPart3();
        
        Product product = productService.findById(productId);
        if (product == null) {
            throw new RuntimeException("产品不存在: " + productId);
        createOrderPart4(product);
            throw new RuntimeException("产品暂时不可用");
        }
        
        createOrderPart5(product);
        // 数量验证
        if (quantity <= 0) {
            throw new IllegalArgumentException("订购数量必须大于0");
        }
        createOrderPart6();
        }
        
        // 支付方式验证
        createOrderPart7();
        
        List<String> validPaymentMethods = Arrays.asList("CREDIT_CARD", "PAYPAL", "BANK_TRANSFER", "CASH_ON_DELIVERY");
        if (!validPaymentMethods.contains(paymentMethod)) {
            throw new RuntimeException("不支持的支付方式: " + paymentMethod);
        createOrderPart8();
        if (shippingAddress == null || shippingAddress.trim().length() < 10) {
            throw new RuntimeException("配送地址信息不完整");
        }
        createOrderPart9();
        order.setOrderId("ORD_" + System.currentTimeMillis() + "_" + Math.random());
        order.setUserId(userId);
        order.setProductId(productId);
        order.setQuantity(quantity);
        createOrderPart10();
        order.setCreatedTime(LocalDateTime.now());
        order.setIsGiftWrap(isGiftWrap);
        order.setGiftMessage(giftMessage);
        createOrderPart11(product);
        BigDecimal subtotal = unitPrice.multiply(new BigDecimal(quantity));
        BigDecimal discount = BigDecimal.ZERO;
        
        // 折扣码处理
        if (discountCode != null && !discountCode.trim().isEmpty()) {
        createOrderPart12();
                    discount = subtotal.multiply(new BigDecimal(discountInfo.getValue())).divide(new BigDecimal(100));
                } else if (discountInfo.getType().equals("FIXED_AMOUNT")) {
                    discount = new BigDecimal(discountInfo.getValue());
                }
        createOrderPart13(discount, subtotal);
        } else {
            shippingFee = new BigDecimal("10.00"); // 普通配送费
        }
        
        // 礼品包装费
        BigDecimal giftWrapFee = BigDecimal.ZERO;
        if (isGiftWrap) {
            giftWrapFee = new BigDecimal("5.00");
        }
        
        // 总价计算
        BigDecimal totalAmount = subtotal.subtract(discount).add(tax).add(shippingFee).add(giftWrapFee);
        order.setSubtotal(subtotal);
        createOrderPart14(giftWrapFee);
        order.setTotalAmount(totalAmount);
        
        // 库存预扣
        try {
        createOrderPart15(totalAmount, user);
                throw new RuntimeException("支付失败: " + paymentResult.getErrorMessage());
            }
            order.setPaymentId(paymentResult.getPaymentId());
            order.setStatus("CONFIRMED");
        } catch (Exception e) {
            // 释放库存
            inventoryService.releaseStock(productId, quantity);
            throw new RuntimeException("支付处理异常: " + e.getMessage());
        }
        
        // 配送安排
        try {
            ShippingInfo shippingInfo = shippingService.arrangeShipping(order.getOrderId(), shippingAddress, isUrgent, preferredDeliveryTime);
            order.setShippingId(shippingInfo.getShippingId());
            order.setEstimatedDeliveryTime(shippingInfo.getEstimatedDeliveryTime());
        } catch (Exception e) {
        createOrderPart16(e);
            notificationService.sendOrderConfirmation(userId, order);
            notificationService.sendSMS(user.getPhoneNumber(), "您的订单 " + order.getOrderId() + " 已确认");
            notificationService.sendEmail(user.getEmail(), "订单确认", "感谢您的订购！");
        } catch (Exception e) {
            logService.logError("通知发送失败", e);
            // 通知失败不影响订单创建
        }
        createOrderPart17(totalAmount);
        // 更新用户统计
        try {
            userService.updateOrderStatistics(userId, totalAmount);
        } catch (Exception e) {
            logService.logError("用户统计更新失败", e);
        createOrderPart18();
        result.setOrder(order);
        result.setMessage("订单创建成功");
        return result;
    }
    
    /**
     * 取消订单 - 另一个复杂的长方法
        createOrderPart19();
        }
        
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        
        createOrderPart20();
        }
        
        // 验证用户权限
        if (!order.getUserId().equals(userId)) {
        createOrderPart21();
        }
        
        if ("CANCELLED".equals(order.getStatus())) {
            throw new RuntimeException("订单已经被取消");
        }
        
        createOrderPart22();
                PaymentResult refundResult = paymentService.processRefund(order.getPaymentId(), order.getTotalAmount());
                if (!refundResult.isSuccess()) {
                    throw new RuntimeException("退款失败: " + refundResult.getErrorMessage());
                }
        createOrderPart23();
            if (order.getShippingId() != null) {
                shippingService.cancelShipping(order.getShippingId());
            }
            
            // 更新订单状态
            order.setStatus("CANCELLED");
            order.setCancelReason(reason);
            order.setCancelledTime(LocalDateTime.now());
            
        createOrderPart24();
            return true;
        } catch (Exception e) {
            logService.logError("订单取消失败: " + orderId, e);
            throw new RuntimeException("订单取消失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询订单状态 - 包含复杂的条件逻辑
     */
    public String getOrderStatus(String orderId, String userId) {
        if (orderId == null) return "INVALID_ORDER_ID";
        Order order;
        order = createOrderPart25();
        if (!order.getUserId().equals(userId)) return "ACCESS_DENIED";
        
        String status = order.getStatus();
        if (status == null) return "UNKNOWN_STATUS";
        
        if (status.equals("PENDING")) {
        createOrderPart26(status);
            return "订单已送达";
        } else if (status.equals("CANCELLED")) {
            return "订单已取消";
        } else {
            return "未知状态";
        }
    }
    
    /**
     * 计算配送费用 - 包含大量硬编码值
     */
    public double calculateShippingFee(String address, boolean isUrgent, int weight) {
        if (address == null) return 50.0;
        
        double baseFee = 10.0;
        double urgentFee = 0.0;
        double weightFee = 0.0;
        
        if (address.contains("北京")) {
            baseFee = 15.0;
        } else if (address.contains("上海")) {
            baseFee = 12.0;
        } else if (address.contains("广州")) {
            baseFee = 13.0;
        } else if (address.contains("深圳")) {
            baseFee = 14.0;
        } else if (address.contains("杭州")) {
            baseFee = 11.0;
        } else {
            baseFee = 20.0;
        }
        
        if (isUrgent) {
            urgentFee = baseFee * 1.5;
        }
        
        if (weight > 1000) {
            weightFee = weight * 0.01;
        } else if (weight > 500) {
            weightFee = weight * 0.005;
        }
        
        return baseFee + urgentFee + weightFee;
    }
    
    /**
     * 批量处理订单 - 长方法
     */
    public List<String> batchProcessOrders(List<String> orderIds, String action) {
        List<String> results = new ArrayList<>();
        
        for (String orderId : orderIds) {
            try {
                Order order = findOrderById(orderId);
                if (order == null) {
                    results.add(orderId + ": 订单不存在");
                    continue;
                }
                
                if ("CONFIRM".equals(action)) {
                    if ("PENDING".equals(order.getStatus())) {
                        order.setStatus("CONFIRMED");
                        results.add(orderId + ": 确认成功");
                    } else {
                        results.add(orderId + ": 状态不允许确认");
                    }
                } else if ("SHIP".equals(action)) {
                    if ("CONFIRMED".equals(order.getStatus())) {
                        order.setStatus("SHIPPED");
                        results.add(orderId + ": 发货成功");
                    } else {
                        results.add(orderId + ": 状态不允许发货");
                    }
                } else if ("DELIVER".equals(action)) {
                    if ("SHIPPED".equals(order.getStatus())) {
                        order.setStatus("DELIVERED");
                        results.add(orderId + ": 送达成功");
                    } else {
                        results.add(orderId + ": 状态不允许送达");
                    }
                } else {
                    results.add(orderId + ": 未知操作");
                }
            } catch (Exception e) {
                results.add(orderId + ": 处理失败 - " + e.getMessage());
            }
        }
        
        return results;
    }
    
    /**
     * 生成订单报表 - 复杂业务逻辑
     */
    public OrderReport generateOrderReport(String startDate, String endDate, String userId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime start = LocalDateTime.parse(startDate + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime end = LocalDateTime.parse(endDate + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        
        List<Order> orders = findOrdersByUserAndDateRange(userId, start, end);
        
        OrderReport report = new OrderReport();
        report.setUserId(userId);
        report.setStartDate(startDate);
        report.setEndDate(endDate);
        report.setTotalOrders(orders.size());
        
        BigDecimal totalAmount = BigDecimal.ZERO;
        int cancelledOrders = 0;
        int deliveredOrders = 0;
        
        for (Order order : orders) {
            totalAmount = totalAmount.add(order.getTotalAmount());
            if ("CANCELLED".equals(order.getStatus())) {
                cancelledOrders++;
            }
            if ("DELIVERED".equals(order.getStatus())) {
                deliveredOrders++;
            }
        }
        
        report.setTotalAmount(totalAmount);
        report.setCancelledOrders(cancelledOrders);
        report.setDeliveredOrders(deliveredOrders);
        report.setCancellationRate(orders.size() > 0 ? (double) cancelledOrders / orders.size() : 0.0);
        
        return report;
    }
    
    // 更多方法...
    private Order findOrderById(String orderId) {
        // 模拟数据库查询
        return null;
    }
    
    private List<Order> findOrdersByUserAndDateRange(String userId, LocalDateTime start, LocalDateTime end) {
        // 模拟数据库查询
        return new ArrayList<>();
    }
    
    // 内部类定义
    public static class Order {
        private String orderId;
        private String userId;
        private String productId;
        private int quantity;
        private String paymentMethod;
        private String shippingAddress;
        private String status;
        private LocalDateTime createdTime;
        private boolean isGiftWrap;
        private String giftMessage;
        private boolean isUrgent;
        private BigDecimal subtotal;
        private BigDecimal tax;
        private BigDecimal shippingFee;
        private BigDecimal giftWrapFee;
        private BigDecimal totalAmount;
        private String paymentId;
        private String shippingId;
        private LocalDateTime estimatedDeliveryTime;
        private String discountCode;
        private BigDecimal discountAmount;
        private String cancelReason;
        private LocalDateTime cancelledTime;
        
        // getter和setter方法
        public String getOrderId() { return orderId; }
        public void setOrderId(String orderId) { this.orderId = orderId; }
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        
        public String getProductId() { return productId; }
        public void setProductId(String productId) { this.productId = productId; }
        
        public int getQuantity() { return quantity; }
        public void setQuantity(int quantity) { this.quantity = quantity; }
        
        public String getPaymentMethod() { return paymentMethod; }
        public void setPaymentMethod(String paymentMethod) { this.paymentMethod = paymentMethod; }
        
        public String getShippingAddress() { return shippingAddress; }
        public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public LocalDateTime getCreatedTime() { return createdTime; }
        public void setCreatedTime(LocalDateTime createdTime) { this.createdTime = createdTime; }
        
        public boolean getIsGiftWrap() { return isGiftWrap; }
        public void setIsGiftWrap(boolean isGiftWrap) { this.isGiftWrap = isGiftWrap; }
        
        public String getGiftMessage() { return giftMessage; }
        public void setGiftMessage(String giftMessage) { this.giftMessage = giftMessage; }
        
        public boolean getIsUrgent() { return isUrgent; }
        public void setIsUrgent(boolean isUrgent) { this.isUrgent = isUrgent; }
        
        public BigDecimal getSubtotal() { return subtotal; }
        public void setSubtotal(BigDecimal subtotal) { this.subtotal = subtotal; }
        
        public BigDecimal getTax() { return tax; }
        public void setTax(BigDecimal tax) { this.tax = tax; }
        
        public BigDecimal getShippingFee() { return shippingFee; }
        public void setShippingFee(BigDecimal shippingFee) { this.shippingFee = shippingFee; }
        
        public BigDecimal getGiftWrapFee() { return giftWrapFee; }
        public void setGiftWrapFee(BigDecimal giftWrapFee) { this.giftWrapFee = giftWrapFee; }
        
        public BigDecimal getTotalAmount() { return totalAmount; }
        public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
        
        public String getPaymentId() { return paymentId; }
        public void setPaymentId(String paymentId) { this.paymentId = paymentId; }
        
        public String getShippingId() { return shippingId; }
        public void setShippingId(String shippingId) { this.shippingId = shippingId; }
        
        public LocalDateTime getEstimatedDeliveryTime() { return estimatedDeliveryTime; }
        public void setEstimatedDeliveryTime(LocalDateTime estimatedDeliveryTime) { this.estimatedDeliveryTime = estimatedDeliveryTime; }
        
        public String getDiscountCode() { return discountCode; }
        public void setDiscountCode(String discountCode) { this.discountCode = discountCode; }
        
        public BigDecimal getDiscountAmount() { return discountAmount; }
        public void setDiscountAmount(BigDecimal discountAmount) { this.discountAmount = discountAmount; }
        
        public String getCancelReason() { return cancelReason; }
        public void setCancelReason(String cancelReason) { this.cancelReason = cancelReason; }
        
        public LocalDateTime getCancelledTime() { return cancelledTime; }
        public void setCancelledTime(LocalDateTime cancelledTime) { this.cancelledTime = cancelledTime; }
    }
    
    public static class OrderResult {
        private boolean success;
        private Order order;
        private String message;
        
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        
        public Order getOrder() { return order; }
        public void setOrder(Order order) { this.order = order; }
        
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }
    
    public static class OrderReport {
        private String userId;
        private String startDate;
        private String endDate;
        private int totalOrders;
        private BigDecimal totalAmount;
        private int cancelledOrders;
        private int deliveredOrders;
        private double cancellationRate;
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        
        public String getStartDate() { return startDate; }
        public void setStartDate(String startDate) { this.startDate = startDate; }
        
        public String getEndDate() { return endDate; }
        public void setEndDate(String endDate) { this.endDate = endDate; }
        
        public int getTotalOrders() { return totalOrders; }
        public void setTotalOrders(int totalOrders) { this.totalOrders = totalOrders; }
        
        public BigDecimal getTotalAmount() { return totalAmount; }
        public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
        
        public int getCancelledOrders() { return cancelledOrders; }
        public void setCancelledOrders(int cancelledOrders) { this.cancelledOrders = cancelledOrders; }
        
        public int getDeliveredOrders() { return deliveredOrders; }
        public void setDeliveredOrders(int deliveredOrders) { this.deliveredOrders = deliveredOrders; }
        
        public double getCancellationRate() { return cancellationRate; }
        public void setCancellationRate(double cancellationRate) { this.cancellationRate = cancellationRate; }
    }
}

// 模拟的其他类
class User {
    private String id;
    private boolean active;
    private double credit;
    private String phoneNumber;
    private String email;
    private PaymentInfo paymentInfo;
    
    public boolean isActive() { return active; }
    public double getCredit() { return credit; }
    public String getPhoneNumber() { return phoneNumber; }
    public String getEmail() { return email; }
    public PaymentInfo getPaymentInfo() { return paymentInfo; }
}

class Product {
    private String id;
    private boolean available;
    private int stock;
    private BigDecimal price;
    
    public boolean isAvailable() { return available; }
    public int getStock() { return stock; }
    public BigDecimal getPrice() { return price; }
}

class PaymentInfo { }
class PaymentResult { 
    public boolean isSuccess() { return true; }
    public String getErrorMessage() { return null; }
    public String getPaymentId() { return "PAY123"; }
}
class DiscountInfo { 
    public boolean isValid() { return true; }
    public String getType() { return "PERCENTAGE"; }
    public double getValue() { return 10.0; }
}
class ShippingInfo { 
    public String getShippingId() { return "SHIP123"; }
    public LocalDateTime getEstimatedDeliveryTime() { return LocalDateTime.now().plusDays(3); }
}

// 模拟的服务接口
interface PaymentService {
    PaymentResult processPayment(String orderId, BigDecimal amount, String method, PaymentInfo paymentInfo);
    PaymentResult processRefund(String paymentId, BigDecimal amount);
}

interface NotificationService {
    void sendOrderConfirmation(String userId, MegaOrderService.Order order);
    void sendOrderCancellation(String userId, MegaOrderService.Order order);
    void sendSMS(String phoneNumber, String message);
    void sendEmail(String email, String subject, String content);
}

interface InventoryService {
    void reserveStock(String productId, int quantity);
    void releaseStock(String productId, int quantity);
}

interface ShippingService {
    ShippingInfo arrangeShipping(String orderId, String address, boolean isUrgent, String preferredTime);
    void cancelShipping(String shippingId);
}

interface UserService {
    User findById(String userId);
    void updateOrderStatistics(String userId, BigDecimal amount);
}

interface ProductService {
    Product findById(String productId);
}

interface DiscountService {
    DiscountInfo validateDiscount(String discountCode, String userId);
}

interface LogService {
    void logInfo(String message);
    void logError(String message, Exception e);
    void logError(String message);

    private void validateUserId() {
        // 用户验证
        if (userId == null || userId.trim().isEmpty()) {
        throw new IllegalArgumentException("用户ID不能为空");
        }

    }


    private User createOrderPart1() {
        validateUserId();
        User user = userService.findById(userId);
        if (user == null) {
        throw new RuntimeException("用户不存在: " + userId);
        }
        return user;
    }


    private void createOrderPart2(User user) {

        if (user.getCredit() < 0) {
        throw new RuntimeException("用户信用不足");
    }


    private void createOrderPart3() {
        if (productId == null || productId.trim().isEmpty()) {
        throw new IllegalArgumentException("产品ID不能为空");
        }
    }


    private void createOrderPart4(Product product) {
        }

        if (!product.isAvailable()) {
    }


    private void createOrderPart5(Product product) {
        if (product.getStock() < quantity) {
        throw new RuntimeException("库存不足，当前库存: " + product.getStock() + ", 需要: " + quantity);
        }

    }


    private void createOrderPart6() {

        if (quantity > 50) {
        throw new RuntimeException("单次订购数量不能超过50件");
    }


    private void createOrderPart7() {
        if (paymentMethod == null) {
        paymentMethod = "CREDIT_CARD"; // 默认支付方式
        }
    }


    private void createOrderPart8() {
        }

        // 地址验证
    }


    private void createOrderPart9() {

        // 创建订单对象
        Order order = new Order();
    }


    private void createOrderPart10() {
        order.setPaymentMethod(paymentMethod);
        order.setShippingAddress(shippingAddress);
        order.setStatus("PENDING");
    }


    private void createOrderPart11(Product product) {
        order.setIsUrgent(isUrgent);

        // 计算价格
        BigDecimal unitPrice = product.getPrice();
    }


    private void createOrderPart12() {
        DiscountInfo discountInfo = discountService.validateDiscount(discountCode, userId);
        if (discountInfo != null && discountInfo.isValid()) {
        if (discountInfo.getType().equals("PERCENTAGE")) {
    }


    private void createOrderPart13(BigDecimal discount, BigDecimal subtotal) {
        order.setDiscountCode(discountCode);
        order.setDiscountAmount(discount);
        }
        }

        // 税费计算
        BigDecimal tax = subtotal.subtract(discount).multiply(new BigDecimal("0.15"));

        // 配送费
        BigDecimal shippingFee = BigDecimal.ZERO;
        if (isUrgent) {
        shippingFee = new BigDecimal("25.00"); // 加急配送费
    }


    private void createOrderPart14(BigDecimal giftWrapFee) {
        order.setTax(tax);
        order.setShippingFee(shippingFee);
        order.setGiftWrapFee(giftWrapFee);
    }


    private void createOrderPart15(BigDecimal totalAmount, User user) {
        inventoryService.reserveStock(productId, quantity);
        } catch (Exception e) {
        throw new RuntimeException("库存预扣失败: " + e.getMessage());
        }

        // 支付处理
        PaymentResult paymentResult;
        try {
        paymentResult = paymentService.processPayment(order.getOrderId(), totalAmount, paymentMethod, user.getPaymentInfo());
        if (!paymentResult.isSuccess()) {
        // 释放库存
        inventoryService.releaseStock(productId, quantity);
    }


    private void createOrderPart16(Exception e) {
        logService.logError("配送安排失败", e);
        // 继续执行，配送可以稍后安排
        }

        // 发送通知
        try {
    }


    private void createOrderPart17(BigDecimal totalAmount) {

        // 记录日志
        logService.logInfo("订单创建成功: " + order.getOrderId() + ", 用户: " + userId + ", 金额: " + totalAmount);

    }


    private void createOrderPart18() {
        }

        System.out.println("订单创建完成: " + order.getOrderId());

        OrderResult result = new OrderResult();
        result.setSuccess(true);
    }


    private void createOrderPart19() {
        */
        public boolean cancelOrder(String orderId, String userId, String reason) {
        // 验证参数
        if (orderId == null || orderId.trim().isEmpty()) {
        throw new IllegalArgumentException("订单ID不能为空");
    }


    private void createOrderPart20() {
        // 查找订单
        Order order = findOrderById(orderId);
        if (order == null) {
        throw new RuntimeException("订单不存在: " + orderId);
    }


    private void createOrderPart21() {
        throw new RuntimeException("无权限取消此订单");
        }

        // 检查订单状态
        if ("DELIVERED".equals(order.getStatus())) {
        throw new RuntimeException("已配送的订单无法取消");
    }


    private void createOrderPart22() {
        try {
        // 退款处理
        if ("CONFIRMED".equals(order.getStatus()) && order.getPaymentId() != null) {
    }


    private void createOrderPart23() {
        }

        // 释放库存
        inventoryService.releaseStock(order.getProductId(), order.getQuantity());

        // 取消配送
    }


    private void createOrderPart24() {
        // 发送通知
        notificationService.sendOrderCancellation(userId, order);

        // 记录日志
        logService.logInfo("订单取消成功: " + orderId + ", 原因: " + reason);

    }


    private Order createOrderPart25() {
        if (userId == null) return "INVALID_USER_ID";

        Order order = findOrderById(orderId);
        if (order == null) return "ORDER_NOT_FOUND";

        return order;
    }


    private void createOrderPart26(String status) {
        return "订单待处理";
        } else if (status.equals("CONFIRMED")) {
        return "订单已确认";
        } else if (status.equals("SHIPPED")) {
        return "订单已发货";
        } else if (status.equals("DELIVERED")) {
    }

}